﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SAKS.Models;
using SAKS.ViewModels;
using SAKS.IServices;
using NHibernate.Transform;
using NHibernate.Linq;
using SAKS.Services.Query;
namespace SAKS.Services
{

    public class MessageServices : IMessageServices
    {
        public NHibernate.ISession Session { get; set; }
        private const string SysUser = "System";

        #region 发消息



        public void SendRemovedFromProjectMessage(string username, Guid projectid)
        {
            if (string.IsNullOrEmpty(username)) throw new ArgumentException("username is null or empty");
            if (projectid == default(Guid)) throw new ArgumentException("projectid is 0");

            var project = Session.Get<Project>(projectid);
            var from = project.Administrator;
            StringBuilder sb = new StringBuilder();
            sb.Append(@"您已经被从项目");
            sb.Append(LinkFor("/project/Details/" + projectid, project.Name));
            sb.Append(@"中移除。");
            MessageReceived mr = new MessageReceived
            {
                Content = sb.ToString(),
                Subject = "您已经被从项目" + project.Name + "中移除",
                ToName = username,
                FromName = SysUser,
                Type = MessageType.System,
                Date = DateTime.Now
            };

            Session.Save(mr);
        }

        public void SendProjectJoinMessage(string username, Guid projectid,string message)
        {

            var project = Session.Get<Project>(projectid);
            var to = project.Administrator;

            StringBuilder sb = new StringBuilder();
            sb.Append("用户");
            sb.Append("<a href='#' class='username'>"+ username+"</a>");
            sb.Append("申请加入您管理的项目");
            sb.Append(LinkFor(@"/Project/Details/" + projectid, project.Name));
            sb.Append("<br />");
            sb.Append(LinkFor(@"/Project/MemberManage/" + projectid + "#tabs-1", "现在去处理"));
            string content = sb.ToString();

            MessageReceived mr = new MessageReceived();

            mr.Content = content;
            mr.Subject = "项目加入申请";
            mr.FromName = SysUser;
            mr.ToName = to.UserName;
            mr.Type = MessageType.System;
            mr.Date = DateTime.Now;

            Session.Save(mr);
        }

        public void SendJoinRequestApproveMessage(string _to, string projectname)
        {
            MessageReceived message = new MessageReceived
            {
                FromName = SysUser,
                ToName = _to,
                Type = MessageType.System,
                Content = "您加入项目" + projectname + "的申请已经被批准。",
                Subject = "您加入项目" + projectname + "的申请已经被批准。",
                Date = DateTime.Now
            };
            Session.Save(message);
        }

        public void SendJoinRequestRejectMessage(string _to, string projectname)
        {
            MessageReceived message = new MessageReceived
            {
                FromName = SysUser,
                ToName = _to,
                Type = MessageType.System,
                Content = "您加入项目" + projectname + "的申请已经被拒绝。",
                Subject = "您加入项目" + projectname + "的申请已经被拒绝。",
                Date = DateTime.Now
            };
            Session.Save(message);
        }
        public void SendMessage(SendMessageModel model)
        {
            SendMessage(model.To, model.From, model.Subject, model.Content);
        }
        public void SendMessage(string _to, string _from, string _subject, string _content)
        {
            if (string.IsNullOrEmpty(_to)) throw new ArgumentException("收件人为空");
            if (string.IsNullOrEmpty(_from)) throw new ArgumentException("发件人为空");
            if (string.IsNullOrEmpty(_subject)) throw new ArgumentException("主题为空");

            MessageReceived mr = new MessageReceived();
            MessageSent ms = new MessageSent();

            mr.Subject = _subject;
            ms.Subject = _subject;
            ms.ToName = _to;
            mr.ToName = _to;
            ms.HasRead = false;
            mr.HasRead = false;
            ms.FromName = _from;
            mr.FromName = _from;
            ms.Content = _content;
            mr.Content = _content;
            ms.Date = DateTime.Now;
            mr.Date = DateTime.Now;

            Session.Save(mr);
            Session.Save(ms);
        }

        #endregion

        #region 读消息

        public MessageSentForRead GetMessageSent(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentException("id is 0");
            var query = from m in Session.Query<MessageSent>()
                        where m.Id == id
                        select new MessageSentForRead()
                        {
                            To = m.ToName,
                            Subject = m.Subject,
                            Content = m.Content,
                            Date = m.Date.ToString()
                        };
            return query.SingleOrDefault();
        }

        public MessageReceivedForRead GetMessageReceived(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentException("id is 0");
            var message = Session.Get<MessageReceived>(id);
            if (message.HasRead == false)
            {
                message.HasRead = true;
                Session.Update(message);
            }
            return new MessageReceivedForRead
            {
                Content = message.Content,
                Subject = message.Subject,
                Date = message.Date.ToString(),
                From = message.FromName,
            };
        }

        #endregion

        #region 删除消息
        public void DeleteMessageSent(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentException("id is 0");
            var message = Session.Get<MessageSent>(id);
            Session.Delete(message);
        }

        public void DeleteMessageReceived(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentException("id is 0");
            var message = Session.Get<MessageReceived>(id);
            Session.Delete(message);
        }
        #endregion

        #region 获取消息数量

        public int GetMessagesUnReadCount(string username)
        {
            if(string.IsNullOrEmpty(username))
                throw new ArgumentException("UserName is null or empty");
            var count = (from m in Session.Query<MessageReceived>()
                         where m.HasRead == false && m.ToName == username
                         select m).Count();
            return count;
        }

        public int GetMessagesReadCount(string UserName)
        {
            if (string.IsNullOrEmpty(UserName))
                throw new ArgumentException("UserName is null or empty");
            return Session.Query<MessageReceived>().Where(m => m.HasRead == true && m.ToName == UserName).Count();
        }

        public int GetMessagesSentCount(string UserName)
        {
            if (string.IsNullOrEmpty(UserName))
                throw new ArgumentException("UserName is null or empty");
            return Session.Query<MessageSent>().Where(m => m.FromName == UserName).Count();
        }

        #endregion

        #region 获取消息列表
        public object[] GetMessagesUnRead(string UserName, int first, int pageSize, out int? totalRecords)
        {
            if (string.IsNullOrEmpty(UserName))
                throw new ArgumentException("UserName is null or empty");
            var search = new PagedMessageReceivedSearch(Session)
            {
                First = first,
                PageSize = pageSize,
                To = UserName,
                HasRead = false
            };
            var result = search.Execute();
            totalRecords = result.TotalItems;
            var query = (from p in result.PageOfResults
                         select new string[]
                        {
                            p.Id.ToString(),
                            p.FromName,
                            p.Subject,
                            p.Date.ToString(),
                        });
            return query.ToArray();
        }

        public object[] GetMessagesRead(string UserName, int first, int pageSize, out int? totalRecords)
        {
            if (string.IsNullOrEmpty(UserName))
                throw new ArgumentException("UserName is null or empty");
            var search = new PagedMessageReceivedSearch(Session)
            {
                First = first,
                PageSize = pageSize,
                To = UserName,
                HasRead = true
            };
            var result = search.Execute();
            totalRecords = result.TotalItems;
            var query = (from p in result.PageOfResults
                         select new string[]
                        {
                            p.Id.ToString(),
                            p.FromName,
                            p.Subject,
                            p.Date.ToString(),
                        });
            return query.ToArray();
        }

        public object[] GetMessagesSent(string UserName, int first, int pageSize, out int? totalRecords)
        {
            if (string.IsNullOrEmpty(UserName))
                throw new ArgumentException("UserName is null or empty");
            var search = new PagedMessageSentSearch(Session)
            {
                First = first,
                PageSize = pageSize,
                From = UserName,
            };
            var result = search.Execute();
            totalRecords = result.TotalItems;
            var query = (from p in result.PageOfResults
                         select new string[]
                        {
                            p.Id.ToString(),
                            p.ToName,
                            p.Subject,
                            p.Date.ToString(),
                        });
            return query.ToArray();
        }


        #endregion


        static string LinkFor(string url, string linktext)
        {
            return "<a href='" + url + "'>" + linktext + "</a>";
        }
    }
}